package com.lzh.template.exception;


import com.lzh.template.common.BaseResponse;
import com.lzh.template.common.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 全局异常处理
 *
 * @author luzhiheng
 */
@Slf4j
@ControllerAdvice(annotations = {RestController.class})
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(LzhException.class)
    public BaseResponse exceptionHandler(LzhException ex) {
        return ResultUtil.error(ex.getCode(), ex.getMessage());
    }


    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public BaseResponse exceptionHandler(BusinessException ex) {
        return ResultUtil.error(ex.getCode(), ex.getMessage());
    }

    /**
     * 校验异常捕获
     *
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse exceptionHandler(MethodArgumentNotValidException e) {
        return ResultUtil.error(600, e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }
}